package com.github.elliot.usercenter.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.util.Optional;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/mono")
public class MonoController {

    @GetMapping("/empty")
    public Mono<String> empty(){
        return Mono.empty();
    }

    @GetMapping("/just")
    public Mono<String> just(){
        return Mono.just("hello flux");
    }

    @GetMapping("/optional")
    public Mono<String> optional(){
        Optional<String> optional = Optional.of("hello flux");
        return Mono.justOrEmpty(optional);
    }

    @GetMapping("/callable")
    public Mono<String> callable(){
        return Mono.fromCallable(() -> {
            Thread.sleep(5000);
            return "data from callable";
        });
    }

    @GetMapping("/future")
    public Mono<String> future(){
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "future result");
        return Mono.fromFuture(completableFuture);
    }

    @GetMapping("/error")
    public Mono<String> error(){
        return Mono.error(new RuntimeException("mock error"));
    }

    @GetMapping("/defer")
    public Mono<String> deferMono() {
        return Mono.defer(() -> Mono.just("Deferred: " + System.currentTimeMillis()));
    }
}
